package com.tools.gensql.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.tools.gensql.enums.DBType;
import org.noear.solon.annotation.Component;

import java.util.Arrays;

@Component
public class MysqlDataQuery implements DataQuery {
    public MysqlDataQuery() {
    }

    public DBType getDatabaseType() {
        return DBType.MYSQL;
    }

    public String getDriver() {
        return "com.mysql.cj.jdbc.Driver";
    }

    public String getUrl(String host, String port, String database, String catalog) {
        return StrUtil.format("jdbc:mysql://{}:{}/{}?useSSL=false", host, port, database);
    }

    public String getQuerySql(String catalog) {
        return "SELECT\n" +
                "\tt.TABLE_SCHEMA AS databaseName,\n" +
                "\tt.TABLE_NAME AS tableName,\n" +
                "\tt.COLUMN_NAME AS columnName,\n" +
                "\tt.COLUMN_TYPE AS columnType,\n" +
                "\tt.IS_NULLABLE AS isNullAble,\n" +
                "\tt.COLUMN_COMMENT AS columnComment,\n" +
                "\tt2.TABLE_COMMENT AS tableComment\n" +
                "FROM\n" +
                "\tinformation_schema.`COLUMNS` t JOIN information_schema.`TABLES` t2 " +
                "ON t2.TABLE_SCHEMA = t.TABLE_SCHEMA AND t2.TABLE_NAME = t.TABLE_NAME\n" +
                "WHERE\n" +
                "\tt.TABLE_SCHEMA = ? AND (t.TABLE_NAME like ? OR t2.TABLE_COMMENT like ? " +
                "OR t.COLUMN_NAME like ? OR t.COLUMN_COMMENT like ?) ORDER BY t.TABLE_NAME limit 500";
    }

    @Override
    public String getTablesQuerySql(String catalog) {
        return "SELECT\n" +
                "\tt.TABLE_NAME AS tableName,\n" +
                "\tt.TABLE_COMMENT AS tableComment\n" +
                "FROM\n" +
                "\tinformation_schema.`TABLES` t\n" +
                "WHERE\n" +
                "\tt.TABLE_SCHEMA = ? ORDER BY t.TABLE_NAME";
    }

    @Override
    public String getQuerySql(int tablesCount, String catalog) {
        var sql = "SELECT\n" +
                "\tt.TABLE_SCHEMA AS databaseName,\n" +
                "\tt.TABLE_NAME AS tableName,\n" +
                "\tt.COLUMN_NAME AS columnName,\n" +
                "\tt.COLUMN_TYPE AS columnType,\n" +
                "\tt.IS_NULLABLE AS isNullAble,\n" +
                "\tt.COLUMN_COMMENT AS columnComment,\n" +
                "\t'' AS tableComment\n" +
                "FROM\n" +
                "\tinformation_schema.`COLUMNS` t\n" +
                "WHERE\n" +
                "\tt.TABLE_SCHEMA = ? AND t.TABLE_NAME IN ({}) ORDER BY t.TABLE_NAME";
        var params = new String[tablesCount];
        Arrays.fill(params, "?");
        return StrUtil.format(sql, ArrayUtil.join(params, ","));
    }
}
